<?php
class db{
    private $link = null;
    function __construct($host, $user, $pass, $name, $long=false, $charset='UTF8') {
        $this->connect($host, $user, $pass, $name, $long, $charset);
    }
    
    function __destruct() {
        $this->close();
    }
    
    function connect($host, $user, $pass, $name, $long=false, $charset='UTF8'){
        if($this->link === null){
            $this->link = !$long?mysql_connect($host, $user, $pass, $charset):mysql_pconnect($host, $user, $pass, $charset);
            $d = mysql_select_db($name, $this->link);
            if(!$d){
                $this->error();
            }
        }
        if(!$this->link){
            $this->error('ERROR::Can\'t Connect DB '.$host.'!');
        }
    }
    
    function error($msg=null){
        if(!$msg){
            $msg = mysql_error($this->link);
        }
        die($msg);
    }
    
    function query($sql){
        $res = mysql_query($sql, $this->link);
        if(!$res){
            $this->error();
        }
        return $res;
    }
    
    function getOne($sql){
        $res = $this->query($sql);
        $row = mysql_fetch_row($res);
        return $row[0];
    }
    
    function getRow($sql){
        $res = $this->query($sql);
        return mysql_fetch_array($res, MYSQLI_ASSOC);
    }

    function getAll($sql){
        $res    = $this->query($sql);
        $data   = array();
        while($row = mysql_fetch_array($res, MYSQLI_ASSOC)){
            $data[] = $row;
        }
        return $data;
    }
    
    /**
     * @access table 表名
     * @access data array数据
     * @access mode true插入false修改
     */
    function exec($table, $data, $where=null){
        $strFv = null;
        foreach ($data as $field => $value){
            $value = stripslashes($value);
            $strFv .= $strFv?', '.$field."='".$value."'":$field."='".$value."'";
        }
        $first = !$where?' INSERT INTO ':'UPDATE ';
        return $this->query($first.$table.' SET '.$strFv.$where);
    }

    function close(){
        mysql_close($this->link);
    }
}
?>